import axios from 'axios'
import { message } from 'vue-voice'

require('promise.prototype.finally').shim()
/**
 * NOTE:
 * - 开发环境：host配置成调试的api地址
 * - 打包发布：host置空已到达所有环境都可使用
 */

const env = process.env.NODE_ENV
const host = `${
  (env && env !== 'development')
      ? (window.GLOBAL_CONFIG.url||'')
      : [
          'http://172.31.46.73:9092',
          'http://172.31.46.2:9093',
          'http://172.31.46.111:9092',
          'http://10.5.143.34:9092',
          'http://10.5.23.46:9092',
      ][0]
}`

const baseURL = `${host}/ocr-ui/`;
axios.defaults.timeout = 50000
axios.defaults.baseURL = baseURL
axios.interceptors.request.use(
  (config) => {
    // 发送请求前做些什么 例如修改配置
    return config
  },
  (error) => {
    // 发送请求错误后做些什么
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(
  (response) => {
    // 请求成功
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

const http = (request, data, query = true) => {
  return new Promise((resolve, reject) => {
    let method = request.method,
      params = (['get', 'delete', 'head'].indexOf(method) > -1 && query) ? { params: data } : { data: data }

      // console.log('http', request, method, params );
      
    axios({ ...request, ...params }).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        if (err.message.indexOf('timeout') === 0) {
          // message.error('请求超时，请重试！')
        }
        reject(err)
      }
    )
  })
}

// eslint-disable-next-line no-unused-vars
const imgSrc = () => {
  axios({
    method: 'get',
    url: `${baseURL}config/info`,
    withCredentials: false,
    data: null,
  })
  .then( result => {
    // console.log('axios getFileServerPath ', result)
      if (result.request.readyState == 4) {
        if( ( ( result.request.status >= 200 && result.request.status < 300 ) || result.request.status == 304 ) && result.request.responseText !== '' ){
          if (JSON.parse(result.request.responseText) && JSON.parse(result.request.responseText).fastdfs){
            console.log('axios getFileServerPath ', JSON.parse(result.request.responseText).fastdfs );
            localStorage.setItem("ImgBasePath", JSON.parse(result.request.responseText).fastdfs );
          }
          else{
            message.error('获取图片基础地址失败！');
          }
        }
      }
  } );
}
// imgSrc();


const url = {
  login: {
    url: '/login',
    method: 'get',
  },
  logout: {
    url: '/logout',
    method: 'post',
  },
  uploadFile: {
    url: 'tool/uploadFile',
    method: 'post',
  },
  // 获取识别结果
  getRecResultUrl: {
    url: '/tool/getRecResult',
    method: 'post',
    timeout: 0,
  },
  //获取目录列表
  getDirectoryList: {
    url: '/file/getAllDirectory',
    method: 'post',
  },
  //获取文件列表
  getFileList: {
    url: '/file/getAllFile',
    method: 'post',
  },
  //获取子文件列表（pdf文件转换成的图片文件列表）
  getSubFileList: {
    url: '/file/getSubFile',
    method: 'post',
  },
  // 导出为word
  exportWord: {
    url: '/file/exportFile',
    method: 'post',
    headers: {
      responseType: 'blob',
    },
  },
  //导出为rtf/html
  exportRtfOrHtml: {
    url: '/file/exportHtmlAndRtf',
    method: 'get',
  },
  //重命名文件
  renameFile: {
    url: '/file/renameFile',
    method: 'post',
  },
  //删除文件
  deleteFile: {
    url: '/file/deleteFile',
    method: 'post',
  },
  //下载文件
  downloadFile: {
    url: '/file/downloadFile',
    method: 'get',
  },
  //ocr识别结果
  doRecognise: {
    url: '/tool/doRecognise',
    method: 'post',
    timeout: 60000,
  },

  // 19.7.22 pcxu new start
  // 截图上传图片
  screenShots: {
    url: 'tool/capture',
    method: 'post',
  },
  // 搜索文件
  searchFile: {
    url: '/file/search',
    method: 'get',
  },
  // 导出文件
  getExportFile: {
    url: '/file/export',
    method: 'get'
  },
  // 用户注册
  register: {
    url: '/register',
    method: 'post'
  },
  userName: {
    url: '/userName',
    method: 'post',
  },

  // 19.7.22 zmwang9 start
  // 批量删除文件
  deleteFiles: {
    url: '/file/batchDelete',
    method: 'post'
  },
  // 批量下载文件
  downloadFiles: {
    url: '/file/batch',
    method: 'post'
  },
  // 标记文件是否打开过，第一次打开时调用
  fileAccess: {
    url: '/file/access',
    method: 'post'
  },
  // 根据识别结果获取其中表格的 html
  getTableHtml: {
    url: '/tool/table/html',
    method: 'post'
  },
  // 编辑预览区域结果
  editOcrResult: {
    url: '/tool/modifyRecResult',
    method: 'post'
  },
    // 新增文件夹
  addFolder: {
    url: '/file/createNewDirectory',
    method: 'post'
  },
  // 删除文件夹
  delFolder: {
    url: '/file/directory',
    method: 'post'
  },
  // 修改文件夹名称
  renameFolder: {
    url: '/file/modifyDirectory',
    method: 'post'
  },
  // 合并导出文件前检查
  checkMergeExport: {
    url: '/file/mergeExport/check',
    method: 'post'
  },
  // 合并导出文件
  mergeExport: {
    url: '/file/mergeExport',
    method: 'get'
  },
  // 批量导出文件前检查
  checkExportBatchFile: {
    url: '/file/export/batch/check',
    method: 'post'
  },
  // 批量导出文件
  getExportBatchFile: {
    url: '/file/export/batch',
    method: 'post'
  },
  // 高级功能
  correctingPic: {
    url: '/file/correctingPic',
    method: 'post'
  },
  // 获取高级功能下识别结果
  getAdvancedRecResult: {
    url: '/tool/getAdvanceRecResult',
    method: 'post',
    timeout: 0,
  },
  // 歪斜图片矫正
  getPictureRotate:{
    url: '/file/pictureRotate',
    method: 'post',
  },

  // 问题反馈提交
  submitFeedBack:{
    url: '/feedback/submitFeedback',
    method: 'post',
  },
  // 获取客服信息
  CustomerServiceInfo:{
    url: 'feedback/customerServiceInfo',
    method: 'get',
  },
  // 获取回复
  FeedBacksInfo:{
    url: '/feedback/feedbacksInfo',
    method: 'get',
  },
  // 回复删除
  DeleteFeedBack:{
    url: '/feedback/deleteFeedback',
    method: 'delete',
  },
  // 获取进度条百分比
  getProgress:{
    url: '/tool/recognize/progress',
    method: 'get',
  },
  // 批量导出文件
  getRecognize: {
    url: '/tool/recognize',
    method: 'post'
  },
  // 批量导出文件
  setPdfpassword: {
    url: '/tool/pdfpass',
    method: 'post'
  },
}

// eslint-disable-next-line no-unused-vars
class Config {
  // 获取文件服务的服务地址
  getFileServerPath() {
    let imgBasePath = '';
    let xhr = new XMLHttpRequest();
    // console.log( 'onreadystatechange0', xhr );
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if ( ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ) && xhr.responseText !== '' ) {
          if (JSON.parse(xhr.responseText) && JSON.parse(xhr.responseText).fastdfs) {
            console.log( 'onreadystatechange1', JSON.parse(xhr.responseText).fastdfs );
            imgBasePath = JSON.parse(xhr.responseText).fastdfs;
          } else {
            message.error('获取图片基础地址失败！')
          }
        }
      }
    }
    xhr.open('get', `${baseURL}config/info`, false);
    xhr.send(null);
    return imgBasePath;
  }
}

// const config = new Config();
// export const ImgBasePath = config.getFileServerPath();

export { http, url, baseURL }
